from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import Rule
import scrapy, time
from w3lib.html import remove_tags
from kyqb_collection_spider.spiders.common import CommonCrawlSpider
from kyqb_collection_spider.items import KyqbCollectionSpiderItem


class GatechSpider(CommonCrawlSpider):
    name = 'gatech'
    start_urls = [
        'http://www.news.gatech.edu/news-room-topics/business-and-economic-development',
        'http://www.news.gatech.edu/news-room-topics/campus-and-community',
        'http://www.news.gatech.edu/earth-and-environment',
        'http://www.news.gatech.edu/news-room-topics/health-and-medicine',
        'http://www.news.gatech.edu/news-room-topics/science-and-technology',
        'http://www.news.gatech.edu/news-room-topics/society-and-culture'
    ]
    custom_settings = {
        'ITEM_PIPELINES': {'kyqb_collection_spider.pipelines.NewImagesPipeline': 5,
                           'kyqb_collection_spider.pipelines.KyqbCollectionSpiderPipeline': 600},
    }

    rules = (
        Rule(LinkExtractor(restrict_xpaths=('//*[@class="pager pager-load-more"]'))
             , callback='parse_item', follow=True),
    )

    def parse_item(self, response):
        div_list = response.xpath('//*[@id="block-system-main"]/div/div/div[1]/div')
        for div in div_list:
            href = response.urljoin(div.xpath('.//a/@href').extract_first())
            if not self.redis.sismember(self.name, href):
                yield scrapy.Request(url=href, callback=self.article)
            # else:
            #     return None

    def article(self, response):
        try:
            item = KyqbCollectionSpiderItem()
            item['data_address'] = response.url
            item['website_name'] = 'GEORGIAINSTITUTE'
            item['spider_name'] = self.name
            item['data_source_type'] = '科技网站'
            item['data_type'] = 'NEWS'
            item['collection_mode'] = 'spider'
            item['collection_time'] = time.strftime('%Y-%m-%d %H:%M:%S')
            timestamp = response.xpath('//*[@class="dateline"]/span[1]/text()').extract_first().strip()
            item['publish_time'] = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(timestamp, "%B %d, %Y"))
            title = response.xpath('//*[@class="news-release-title"]/text()').extract_first()
            item['title'] = remove_tags(title)
            item['abstract'] = None
            item['topic'] = None
            ps = response.xpath('//*[@class="content node-body clearfix"]/p')
            texts = []
            for p in ps:
                containers = p.xpath('.//text()').extract()
                for container in containers:
                    text = remove_tags(container)
                    texts.append(text)
            item['text'] = '\n'.join(texts)
            author = response.xpath('//*[@class="dateline-details clearfix"]/div[1]/text()').extract_first()
            item['author'] = remove_tags(author).replace('By', '').replace('|', '').strip()
            image_urls = set()
            urls = response.xpath('//*[@id="hero-wrapper-description"]//img/@src').extract()
            for url in urls:
                image_urls.add(url)
            item['image_urls'] = list(image_urls)
            yield item
        except Exception as e:
            self.logger.debug(f"采集错误:{response.url}\n{e}")
